package net.sunofbeach.blog.services.impl;

import lombok.extern.slf4j.Slf4j;
import net.sunofbeach.blog.dao.HsHouseDao;
import net.sunofbeach.blog.pojo.HsHouse;
import net.sunofbeach.blog.response.ResponseResult;
import net.sunofbeach.blog.services.IHsHouseService;
import net.sunofbeach.blog.utils.getDistance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author masterGuo
 * @net www.lolxiaoguo.cn
 * @date 2022/6/8 19:33
 */

@Slf4j
@Service
@Transactional
public class HsHouseServiceImpl extends BaseService implements IHsHouseService {

    @Autowired
    private HsHouseDao hsHouseDao;





    @Override
    public ResponseResult list5House(Double lat, Double lon) {

        List<HsHouse> all;
        all = hsHouseDao.findAll();

        List<HsHouse> hsHouses = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            HsHouse hsHouse = all.get(i);
            Double latitude = Double.parseDouble(hsHouse.getLatitude());
            Double longitude = Double.parseDouble(hsHouse.getLongitude());
            //1.如果经纬度差的很大，就不计算了
            Double dis = getDistance.getDis(latitude, longitude, lat, lon);
            hsHouse.setDistance(dis);
            hsHouses.add(hsHouse);
        }


        hsHouses.sort(new myComprator());


        if (hsHouses.size() < 5&&hsHouses.size()>0) {
            return ResponseResult.SUCCESS("获取列表成功").setData(hsHouses);
        } else {
            return ResponseResult.SUCCESS("获取列表成功").setData(hsHouses.subList(0, 5));
        }

    }


    public static class myComprator implements Comparator<HsHouse> {

        @Override
        public int compare(HsHouse o1, HsHouse o2) {

            double a1 = o1.getDistance()*10000;
            double a2 = o2.getDistance()*10000;

            return (int) (a1 - a2);

        }
    }

}
